package cn.xiaohello.TCP;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;

/**
 * 客户端程序，向服务器发送消息，并获得响应信息。
 * 
 * @author XIAO
 *
 */
public class SocketTestClient {

	public static void main(String[] args) {
		InputStream is = null;
		OutputStream os = null;
		Socket socket = null;
		try {
			// 链接本机
			InetAddress address = InetAddress.getLocalHost();
			// 端口号80
			int port = 80;
			// 创建socket链接
			// Socket socket = new Socket("127.0.0.1", port);
			socket = new Socket(address, port);
			System.out.println("客户机已启动。。。");
			// 获取输出流，向服务器发送数据
			os = socket.getOutputStream();
			os.write("i am client".getBytes());
			// 接收服务器反馈的数据
			is = socket.getInputStream();
			byte[] b = new byte[1024];
			int n = is.read(b);
			// 输出反馈的数据
			System.out.println("服务器的反馈信息：" + new String(b, 0, n));
		} catch (UnknownHostException e) {
			// do nothing
		} catch (IOException e) {

		} finally {
			// 关闭链接
			try {
				is.close();
				os.close();
				socket.close();
			} catch (IOException e) {
				// do nothing
			}

		}

	}

}
